import { memo, useState } from 'react'
import { Button, Modal, Form, Input } from 'antd';
import { FileAddOutlined } from '@ant-design/icons';
import { useMessage } from '@/hooks/useMessage';
import { createKnowledgeBase } from '@/views/KnowledgeBase/pages/list/api';
import style from './index.module.less'

const { TextArea } = Input;

const AddKnowledgeBase = ({ onSuccess }) => {
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [loading, setLoading] = useState(false)
    const [form] = Form.useForm();
    const { error, contextHolder } = useMessage()

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        form.resetFields();
    };

    const handleOk = async () => {
        try {
            setLoading(true);
            const values = await form.validateFields();
            // 关键：owner 必须是 user_id
            const owner = localStorage.getItem('userId');
            if (!owner) {
                error({ content: '用户未登录或userId丢失' });
                setLoading(false);
                return;
            }
            const res = await createKnowledgeBase({
                name: values.name,
                description: values.description,
                owner
            });
            if (res.code === 200) {
                setIsModalOpen(false);
                form.resetFields();
                if (onSuccess) onSuccess(); // 新建成功后刷新列表
            } else {
                error({ content: res.msg || '新建失败' });
            }
        } catch (e) {
            // 校验失败或接口异常
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            {contextHolder}
            <Button 
                type='default' 
                className={style.box}
                onClick={showModal}
            >
                <FileAddOutlined className={style.firIcon} />
                新建知识库
            </Button>
            <Modal 
                title={<div className={style.modalTitle}>新建知识库</div>}
                open={isModalOpen}
                okText={'确认'}
                cancelText={'取消'}
                destroyOnClose={true}
                confirmLoading={loading}
                onOk={handleOk}
                onCancel={handleCancel}
                className={style.knowledgeBaseModal}
                width={600}
            >
                <Form 
                    form={form}
                    validateTrigger='onChange' 
                    colon={false}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    className={style.formContainer}
                >
                    <Form.Item 
                        name='name' 
                        label='知识库名称'
                        rules={[
                            { required: true, message: '请输入知识库名称' }
                        ]}
                    >
                        <Input placeholder="请输入知识库名称" />
                    </Form.Item>
                    <Form.Item 
                        name='description' 
                        label='知识库描述'
                    >
                        <TextArea 
                            placeholder="请输入知识库描述" 
                            rows={4}
                            className={style.textArea}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}

export const MemoAddKnowledgeBase = memo(AddKnowledgeBase)